<template>
  <!-- 下拉刷新 -->
  <van-pull-refresh v-model="state.isRefreshing" @refresh="onLoad(true)">
    <!-- 上拉加载更多 -->
    <van-list v-model:loading="state.loading" :finished="state.finished" finished-text="没有更多了" @load="onLoad">
      <!-- 文章 Item 项 -->
      <art-item v-for="item in artList" :key="item.art_id.toString()" :article="item" @remove-article="removeArticle"></art-item>
    </van-list>
  </van-pull-refresh>
</template>

<script>
import { getArticleList } from '@/api/homeAPI'
import { ref } from 'vue'
import ArtItem from '@/views/Article/ArticleItem.vue'

export default {
  name: 'ArticleList',
  props: {
    // 频道的 Id
    channelId: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    // 文章列表的数据
    const artList = ref([])

    // 上拉加载更多的状态
    const state = ref({
      loading: false,
      finished: false,
      isRefreshing: false
    })

    // 上拉触底的处理函数
    const onLoad = async isRefresh => {
      const { data: res } = await getArticleList(props.channelId)
      if (res.message === 'OK') {
        if (isRefresh) {
          // 新数据拼接数旧据
          artList.value = [...res.data.results, ...artList.value]
          // 关闭下拉刷新效果
          state.value.isRefreshing = false
        } else {
          // 旧数据拼接新数据
          artList.value = [...artList.value, ...res.data.results]
          // 关闭 loading 效果
          state.value.loading = false
        }
        // 判断是否还有下一页数据
        if (res.data.results.length === 0) {
          state.value.finished = true
        }
      }
    }

    // 从列表中删除文章
    const removeArticle = artId => {
      artList.value = artList.value.filter(x => x.art_id.toString() !== artId)
    }

    return {
      artList,
      state,
      onLoad,
      removeArticle
    }
  },
  components: {
    ArtItem
  }
}
</script>

<style lang="less" scoped>
</style>
